require('express-async-errors');
const path = require('path');
const express = require('express');
const app = express();
const connectDB = require('./db/connectDB');
const notFoundMD = require('./middleware/not-found');
const errCaptureMiddleware = require('./middleware/err-capture');
require('dotenv').config();
const PORT = process.env.PORT;

const swaggerUI = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');

app.use(express.static(path.resolve(__dirname, '..', 'client', 'build')));
app.use(express.json());

// 安全策略
const mouteSecurity = require('./utils/mouteSecurity');
mouteSecurity(app);

// 注册路由
const mountRoutes = require('./utils/mouteRouter');
mountRoutes(app);

// 开发模式
if (process.env.NODE_ENV !== 'PROD') {
   app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocument));
   app.get('*', (req, res) => {
      res.send(`<h1>jobs API</h1><a href="/api-docs"> Document</a>`);
   });
} else {
   app.get('*', (req, res) => {
      res.sendFile(
         path.resolve(__dirname, '..', 'client', 'build', 'index.html')
      );
   });   
}


app.use(notFoundMD); // 匹配其他未定义
app.use(errCaptureMiddleware); // 全局错误捕获

const start = async () => {
   try {
      await connectDB(process.env.MONGO_URI);
      app.listen(PORT, console.log(`Server is running on port ${PORT}`));
   } catch (error) {
      console.log(error);
   }
};

start();
